package dan.android.guardianlocation.gps;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class Tracker extends Service implements LocationListener {

	private Context context;
	protected LocationManager locationManager;
	private boolean isGPSEnabled;
	private boolean isNetworkEnabled;
	private boolean canGetLocation;
	public int changes;

	public Tracker(Context cntx) {
		context = cntx;
		isCanGetLocation();
		changes = 0;
	}

	private boolean isCanGetLocation() {
		getService();
		canGetLocation = locationManager != null && (isGPSEnabled || isNetworkEnabled);
		return canGetLocation;
	}

	private void getService() {
		locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
		isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
	}

	public Location getCurrentLocation(long distance, long time) {
		try {
			Location current = null;
			if (isCanGetLocation()) {
				if (isGPSEnabled) {
					locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time * 1000, distance, this);
					Log.d("GPS", "Enabled");
					current = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
					if (current != null)
						return current;
				}

				if (isNetworkEnabled) {
					locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time * 1000, distance, this);
					Log.d("Network", "Enabled");
					current = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
					if (current != null)
						return current;
				}
			}
			return current;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		Location newLocation = getCurrentLocation(10, 5);
		Log.d("Latitude", newLocation.getLatitude() + "");
		Log.d("Longitud", newLocation.getLongitude() + "");
		changes += 1;
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
